from tkinter import *
class LocanCalculator:
    def __init__(self):
        window = Tk()
        window.title("贷款计算器")

        Label(window,text='年利率：').grid(row=1,column=1,sticky=W)
        Label(window,text='年份：').grid(row=2,column=1,sticky=W)
        Label(window,text='金额：').grid(row=3,column=1,sticky=W)
        Label(window,text='月供：').grid(row=4,column=1,sticky=W)
        Label(window,text='总额：').grid(row=5,column=1,sticky=W)


        self.annualInteresRateVar = StringVar()
        Entry(window,textvariable=self.annualInteresRateVar,justify=RIGHT).grid(row=1,column=2)

        self.numberOfYearsVar = StringVar()
        Entry(window,textvariable=self.numberOfYearsVar,justify=RIGHT).grid(row=2,column=2)

        self.loanAmountVar = StringVar()
        Entry(window,textvariable=self.loanAmountVar,justify=RIGHT).grid(row=3,column=2)

        self.monthlyPayMentVar = StringVar()
        lblMonthLyPayment = Label(window,textvariable=self.monthlyPayMentVar,justify=RIGHT).grid(row=4,column=2,sticky=E)

        self.totalPayMentVar = StringVar()
        lblTotalPayment = Label(window, textvariable=self.totalPayMentVar, justify=RIGHT).grid(row=5, column=2, sticky=E)

        btComputePayment = Button(window,text='计算',command=self.computePayment).grid(row=6,column = 2,sticky=E)


        window.mainloop()

    def computePayment(self):

        monthlyPayment = self.getMonthPayment(float(self.loanAmountVar.get()),float(self.annualInteresRateVar.get())/1200,int(self.numberOfYearsVar.get()))

        self.monthlyPayMentVar.set(format(monthlyPayment,"10.2f"))
        totalPayment = float(self.monthlyPayMentVar.get()) * 12 * int(self.numberOfYearsVar.get())
        self.totalPayMentVar.set(format(totalPayment,'10.2f'))

    def getMonthPayment(self,loanAmount,monthlyInterestRate,numberOfYears):
        monthlyPayment = loanAmount * monthlyInterestRate / ( 1 - 1/ (1+monthlyInterestRate) ** (numberOfYears*12))
        return monthlyPayment

LocanCalculator()